﻿import pygame
import sys

# 初始化pygame
pygame.init()

# 定义一些颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (150, 150, 150)
CURSOR_COLOR = (0, 255, 0)  # 光标颜色

# 屏幕尺寸
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('带有光标和左右键切换功能的输入框')

# 字体设置
font = pygame.font.Font(None, 36)

# 输入框的位置和大小
input_box = pygame.Rect(100, 100, 400, 50)
text = ''
cursor_pos = 0  # 光标位置
active = False
last_key_time = None
repeat_interval = 0.2  # 按键重复间隔（对于左右键）
cursor_blink_interval = 0.5  # 光标闪烁间隔
cursor_visible = True
last_cursor_blink_time = None

def draw_input_box(screen, rect, text, cursor_pos, cursor_visible):
    # 绘制输入框
    pygame.draw.rect(screen, WHITE, rect, 2)
    
    # 渲染文本
    txt_surface = font.render(text, True, BLACK)
    screen.blit(txt_surface, (rect.x + 5, rect.y + 5))
    
    # 获取文本的宽度
    cursor_width, _ = font.size(text[:cursor_pos])
    
    # 绘制光标
    if cursor_visible:
        cursor_rect = pygame.Rect(rect.x + 5 + cursor_width, rect.y + 5, 2, font.get_height())
        pygame.draw.rect(screen, CURSOR_COLOR, cursor_rect)

# 主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if input_box.collidepoint(event.pos):
                active = True
                cursor_pos = len(text)  # 点击输入框时，将光标移到文本末尾
            else:
                active = False
        elif event.type == pygame.KEYDOWN:
            if active:
                if event.key == pygame.K_LEFT:
                    if cursor_pos > 0:
                        cursor_pos -= 1
                elif event.key == pygame.K_RIGHT:
                    if cursor_pos < len(text):
                        cursor_pos += 1
                elif event.key == pygame.K_BACKSPACE:
                    if cursor_pos > 0:
                        text = text[:cursor_pos-1] + text[cursor_pos:]
                        cursor_pos -= 1
                else:
                    # 过滤非打印字符
                    if event.unicode.isprintable():
                        text = text[:cursor_pos] + event.unicode + text[cursor_pos:]
                        cursor_pos += 1

    # 处理光标闪烁
    current_time = pygame.time.get_ticks() / 1000.0
    if last_cursor_blink_time is None:
        last_cursor_blink_time = current_time
    if current_time - last_cursor_blink_time >= cursor_blink_interval:
        cursor_visible = not cursor_visible
        last_cursor_blink_time = current_time

    # 填充屏幕背景
    screen.fill((30, 30, 30))
    
    # 绘制输入框和光标
    draw_input_box(screen, input_box, text, cursor_pos, cursor_visible)
    
    # 更新屏幕
    pygame.display.flip()

    # 控制帧率
    pygame.time.Clock().tick(60)

# 退出pygame
pygame.quit()
sys.exit()
